<?php
namespace app\api\controller;
/**
 * 邮箱-API接口
 * User: huangzhen
 * Date: 2021/01/14
 */

use think\facade\Request;
use think\facade\Db;
use PHPMailer\PHPMailer\PHPMailer;


class EmailSend
{
    /**
     * 构造方法
     * @param Request $request Request对象
     */
    public function __construct(Request $request)
    {
    }

    public static function sendEmail($type,$data)
    {
        $email = explode("," ,$data['email']);
        if(count($email) >1){
            foreach($email as $k=>$v){
                $data['email'] = $v;
                self::sends($type , $data);
            }
        }else{
            return self::sends($type , $data);
        }
    }

    public static function sends($type,$data)
    {
        $user_id    = $data['user_id'] ?? 0;
        $email      = $data['email'];
        $desc       = $data['desc'];
        if($type == 'check_login' || $type == 'check_pwd' || $type == 'manage_email_check' || $type == 'check_zhuc'){
            $code = $data['code'];
            $request = "email：{$email} , code：{$code}";
            $Subject = "The verification code for CardEcho!";
            $remark_msg = '';
            if($type == 'check_login'){
                $remark_msg = '(user login)';
            }else if($type == 'check_pwd'){
                $remark_msg = '(change user password)';
            }else if($type == 'check_zhuc'){
                $remark_msg = '(user reg)';
            }
            $body = "Your verification code {$remark_msg} is: <span style='color:red;font-size: 20px;'>"
                . $code . "</span> , The verification code is valid for 5 minutes. Please do not reply to this email!"; //该邮件内容;
        }elseif ($type == 'user_fund'){
            $request = "email：{$email} ";
            $Subject = "{$email} Funding -- CardEcho";
            $body = $desc;
        }elseif ($type == 'user_fund_check'){
            $request = "email：{$email} ";
            $Subject = "Funding Review Notice -- CardEcho";
            $body = $desc;
        }elseif ($type == 'user_exception'){
            $request = "email：{$email} ";
            $Subject = "User Data Exception -- CardEcho";
            $body = $desc;
        }elseif ($type == 'contact_us'){
            $request = "email：{$email} ";
            $list = Db::name('setting')->where(['key' => 'contact_us_email_title'])->find();
            $apply_email_title = $list['value'] ?? "Application accepted -- BetterEpay";
            $Subject = $apply_email_title;
            $body = $desc;
        }elseif ($type == 'get_demo'){
            $request = "email：{$email} ";
            $list = Db::name('setting')->where(['key' => 'get_demo_email_title'])->find();
            $apply_email_title = $list['value'] ?? "Application accepted -- BetterEpay";
            $Subject = $apply_email_title;
            $body = $desc;
        }elseif ($type == 'get_demo_manage') {
            $request = "email：{$email} ";
            $Subject = "User Enter Get Demo.-- CardEcho";
            $body = $desc;
        }elseif ($type == 'contact_us_manage') {
            $request = "email：{$email} ";
            $Subject = "User Enter Contact Us. -- CardEcho";
            $body = $desc;
        }elseif ($type == 'debt_month') {
            $request = "email：{$email} ";
            $Subject = "CardEcho 账号通知";
            $body = $desc;
        }elseif ($type == 'decline_notice' || $type == 'ice_user'
            || $type == 'all_user_send' || $type == 'bank_to_amount'
            || $type == 'bank_3_to_amount' || $type == 'bank_1_to_amount' || $type == 'usdt_fund_amount') {
            $request = "email：{$email} ";
            $Subject = $data['title'];
            $body = $desc;
        } elseif ($type == 'user_idCard_check') {
            $request = "email：{$email} ";
            $Subject = "CardEcho 人脸识别出错";
            $body = $desc;
        }elseif ($type == 'oy_user_up_email_check') {
            $request = "email：{$email} ";
            $Subject = "cardEcho USDT address update";
            $body = "Your verification code is: <span style='color:red;font-size: 20px;'>"
                . $data['code'] . "</span> , The verification code is valid for 1 minutes. Please do not reply to this email!"; //该邮件内容;
        }else{
            $request = "email：{$email} ";
            $Subject = "CardEcho account via notification";
            $body = 'Your account (' . $email  . ') has been approved';
        }

        $mail = new PHPMailer();
        $mail->isSMTP(); // 启用SMTP
        $mail->Host     ="smtp.gmail.com"; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPSecure = "ssl"; //目前规定必须使用ssl，非ssl的协议已经不支持了
        $mail->Port     = 465; //端口号
        //$mail->SMTPDebug = 2; //用于debug PHPMailer信息
        $mail->SMTPAuth = true; //启用smtp认证
        $mail->Username = "verify@cardecho.com"; //你的邮箱名
        $mail->Password = 'cecceytiohekfxba' ; //邮箱授权码，注意是授权码，不是登录密码
        $mail->From     = "verify@cardecho.com"; //发件人地址（也就是你的邮箱地址）
        $mail->FromName = "CardEcho"; //发件人姓名
        $mail->AddAddress($email); //收件人地址
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(true); // 是否HTML格式邮件
        $mail->CharSet  ="utf-8"; //设置邮件编码
        $mail->Subject  = $Subject;  //添加该邮件的主题
        $mail->Body     = $body;
        $result = $mail->Send();
        $blog   = true;
        $log_code   = 200;
        $response = 'ok';
        if(!$result){
            $log_code   = 500;
            $blog   = false;
            $response = $mail->ErrorInfo;
        }
        Db::name('api_other')->save([
            'user_id' => $user_id,
            'name'    => $type,
            'ip'      => ip(),
            'request' => $request,
            'code'    => $log_code,
            'response'=> $response,
            'desc'    => ($type == 'ice_user')?substr($desc,0,100):$desc,
            'ctime'   => getUtcTime()
        ]);
        return $blog;
    }

    public static function sendGridEmail($type,$data)
    {
        $pt_name    = "CardEcho";
        $user_id    = $data['user_id'] ?? 0;
        $email      = $data['email'];
        $title      = $data['title'] ?? $pt_name . ' Send';
        $body       = $data['body'] ??  $pt_name .  ' Support';
        $request    = $data['body'] ??  $pt_name .  ' Support';
        if($type == 'check_login'
            || $type == 'check_pwd'
            || $type == 'check_zhuc'
            || $type == 'manage_email_check'){
            $code = $data['code'];
            $json_eamil = $email;
            if(is_array($json_eamil)){
                $json_eamil = json_encode($email);
            }
            $request = "email：{$json_eamil} , code：{$code}";
            $title = "The verification code for {$pt_name}!";
            $remark_msg = '';
            if($type == 'check_login'){
                $remark_msg = '(user login)';
            }else if($type == 'check_pwd'){
                $remark_msg = '(change user password)';
            }else if($type == 'check_zhuc'){
                $remark_msg = '(user reg)';
            }
            $body = "Your verification code {$remark_msg} is:"
                . "<span style='color:red;font-size: 20px;'>{$code}</span>" . " , The verification code is valid for 1 minutes. Please do not reply to this email!"; //该邮件内容;
        }

        $apiKey     = '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';
        $sg         = new SendGridService($apiKey);

        $resp = $sg->sendMail(
            $email,
            $title,
            $body,
            ['email'=>'verify@cardecho.com','name'=> $pt_name . ' verification']
        );
        $blog = true;
        $log_code   = $resp->statusCode();
        $desc = '';
        if(substr($resp->statusCode(),0,1) != '2'){
            $desc = $resp->body();
            $blog = false;
        }
        Db::name('api_other')->save([
            'user_id' => $user_id,
            'name'    => $type,
            'ip'      => ip(),
            'request' => $request,
            'code'    => $log_code,
            'response'=> $blog,
            'desc'    => $desc,
            'ctime'   => getUtcTime()
        ]);
        return $blog;
    }
}